package tech.wetech.admin3.util;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.DID;
import tech.wetech.admin3.sys.service.DIDService;

import java.util.List;

@Slf4j
@Component
public class DIDCreateUtil {
  private LianduAPIUtils lianduAPIUtil;
  private DIDService didService;
  private HashUtil hashUtil;
  public DIDCreateUtil(DIDService didService, LianduAPIUtils lianduAPIUtil, HashUtil hashUtil){
    this.didService = didService;
    this.lianduAPIUtil = lianduAPIUtil;
    this.hashUtil = hashUtil;
  }

  public String generateSerial(String kind){
//    Integer count = didService.count() + 1;
//    String end4 = String.format("%04d", count);

    Integer maxId = didService.findMaxId();
    if (maxId == null) {
      maxId = 1001;
    } else {
      maxId += 1001;
    }
    String end4 = String.format("%04d", maxId);

    String serial = "";
    if (kind.equals("x")){
      serial = "szr" + "x" + "000000" + GetDateUtil.getYyyyMMdd() + end4;
    }else if (kind.equals("z")){
      serial = "szr" + "z" + "000000" + GetDateUtil.getYyyyMMdd() + end4;
    } else {
      throw new AooUserException("虚拟人类型错误，只能为'x'或'z'");
    }
    log.info("生成did身份编号================" + serial);
    return serial;
  }


  public DID createDID(
    String kind,
    String digitalName,
    String owner,
    String imageUrls,
    String imageHashes,
    String modelFileUrls,
    String modelFileHashes
  ){
    try {
      DID existingDid = didService.findByName(digitalName);
      if (existingDid != null) {
        throw new AooUserException("虚拟人已存在，请确认");
      }

      String serial = generateSerial(kind);
      JSONObject res = lianduAPIUtil.create();
      System.out.println("创建did角色---" + res);

      if (res.getStr("status").equals("ok")){
        DID did = new DID();
        did.setName(digitalName);
        did.setType("类型1");
        did.setSerial(serial);
        did.setDidNo(res.getStr("did"));
        did.setOwner(owner);
        did.setAddr(res.getStr("addr"));
        did.setUkey(res.getStr("ukey"));
        did.setTxhash(res.getStr("txhash"));
        did.setStartDate(GetDateUtil.getYyyyMMddHHmmss());
        did.setImageUrls(imageUrls);
        did.setImageHashes(imageHashes);
        did.setModelFileUrls(modelFileUrls);
        did.setModelFileHashes(modelFileHashes);
//        System.out.println(did);
        return didService.createDID(did);
      } else {
        throw new AooUserException(res.getStr("message"));  // 链度创建did请求错误
      }
    } catch (AooUserException e) {
      throw new AooUserException(e.getMessage()); // 生成编号错误
    }
  }
}
